package com.ylkj.dao;

import com.mysql.cj.jdbc.ConnectionImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.*;
import java.util.concurrent.Executor;

@Slf4j
public class RdsUtils {
    private static final String driver = "com.mysql.cj.jdbc.Driver";
    private static final int loginTimeout = 60;
    private static final long checkInterval = 1000 * 60 * 10;

    {
        try {
            log.info("load driver:{}", driver);
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage(), e);
            System.exit(1);
        }
    }

    private final RdsConfig rdsConfig;
    private final List<CustomConnection> connections;
    private boolean closed = false;

    public RdsUtils(RdsConfig rdsConfig) {
        this.rdsConfig = rdsConfig;
        this.connections = Collections.synchronizedList(new ArrayList<>());
        DriverManager.setLoginTimeout(loginTimeout);
    }

    public Connection getConnection() {
        if (log.isDebugEnabled()) {
            log.debug("获取连接 {}", rdsConfig);
        }
        if (closed) {
            throw new RuntimeException("RdsUtils is closed");
        }
        if (connections.isEmpty()) {
            try {
                Connection proxy = DriverManager.getConnection(rdsConfig.getUrl(), rdsConfig.getUsername(), rdsConfig.getPassword());
                if (log.isDebugEnabled()) {
                    log.debug("新建连接成功。");
                }
                return new CustomConnection(proxy);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
                return null;
            }

        }
        synchronized (connections) {
            if (connections.isEmpty()) {
                return getConnection();
            }
            CustomConnection connection = connections.remove(connections.size() - 1);
            if (connection.check()) {
                if (log.isDebugEnabled()) {
                    log.debug("获取连接成功。");
                }
                return connection;
            }
            return getConnection();
        }
    }

    @SneakyThrows
    public int getPort() {
        String port = getProperty("port");
        if (port == null || port.isEmpty()) {
            return 3306;
        }
        return Integer.parseInt(port);
    }

    public String getDatabaseName() throws SQLException {
        return getProperty("dbname");
    }

    public String getHost() throws SQLException {
        return getProperty("host");
    }

    private String getProperty(String key) throws SQLException {
        CustomConnection connection = (CustomConnection) getConnection();
        String property = connection.getProperties().getProperty(key);
        connection.close();
        return property;
    }

    public long getServerId() throws SQLException {
        CustomConnection connection = (CustomConnection) getConnection();
        ResultSet rs = connection.createStatement()
                .executeQuery("SHOW VARIABLES LIKE 'server_id'");

        long serverId = -1;
        if (rs.next()) {
            serverId = Long.parseLong(rs.getString("Value"));
        }
        connection.close();
        return serverId;
    }

    public void close() {
        log.info("close RdsUtils");
        closed = true;
        if (connections.isEmpty()) {
            return;
        }
        synchronized (connections) {
            connections.forEach(CustomConnection::realClose);
            connections.clear();
        }
    }


    public class CustomConnection implements Connection {
        private final Connection proxy;
        private long lastCheckConnection;
        private Properties properties;

        public CustomConnection(Connection proxy) {
            this.proxy = proxy;
            this.lastCheckConnection = System.currentTimeMillis();
        }

        public boolean check() {
            if (System.currentTimeMillis() - lastCheckConnection > checkInterval) {
                if (proxy instanceof ConnectionImpl) {
                    try {
                        ((ConnectionImpl) proxy).ping();
                        lastCheckConnection = System.currentTimeMillis();
                    } catch (SQLException e) {
                        log.warn(e.getMessage(), e);
                        return false;
                    }
                } else {
                    try {
                        return proxy.isValid(60);
                    } catch (SQLException e) {
                        log.warn(e.getMessage(), e);
                        return false;
                    }
                }
            }
            return true;
        }

        public Properties getProperties() {
            if (properties != null) {
                return properties;
            }
            if (proxy instanceof ConnectionImpl) {
                properties = ((ConnectionImpl) proxy).getProperties();
            } else {
                properties = new Properties();
            }
            return properties;
        }

        @Override
        public void close() throws SQLException {
            synchronized (connections) {
                connections.add(this);
            }
        }

        public void realClose() {
            try {
                proxy.close();
                closed = true;
            } catch (SQLException e) {
                log.warn(e.getMessage(), e);
            }
        }

        @Override
        public Statement createStatement() throws SQLException {
            return proxy.createStatement();
        }

        @Override
        public PreparedStatement prepareStatement(String sql) throws SQLException {
            return proxy.prepareStatement(sql);
        }

        @Override
        public CallableStatement prepareCall(String sql) throws SQLException {
            return proxy.prepareCall(sql);
        }

        @Override
        public String nativeSQL(String sql) throws SQLException {
            return proxy.nativeSQL(sql);
        }

        @Override
        public void setAutoCommit(boolean autoCommit) throws SQLException {
            proxy.setAutoCommit(autoCommit);
        }

        @Override
        public boolean getAutoCommit() throws SQLException {
            return proxy.getAutoCommit();
        }

        @Override
        public void commit() throws SQLException {
            proxy.commit();
        }

        @Override
        public void rollback() throws SQLException {
            proxy.rollback();
        }


        @Override
        public boolean isClosed() throws SQLException {
            return proxy.isClosed();
        }

        @Override
        public DatabaseMetaData getMetaData() throws SQLException {
            return proxy.getMetaData();
        }

        @Override
        public void setReadOnly(boolean readOnly) throws SQLException {
            proxy.setReadOnly(readOnly);
        }

        @Override
        public boolean isReadOnly() throws SQLException {
            return proxy.isReadOnly();
        }

        @Override
        public void setCatalog(String catalog) throws SQLException {
            proxy.setCatalog(catalog);
        }

        @Override
        public String getCatalog() throws SQLException {
            return proxy.getCatalog();
        }

        @Override
        public void setTransactionIsolation(int level) throws SQLException {
            proxy.setTransactionIsolation(level);
        }

        @Override
        public int getTransactionIsolation() throws SQLException {
            return proxy.getTransactionIsolation();
        }

        @Override
        public SQLWarning getWarnings() throws SQLException {
            return proxy.getWarnings();
        }

        @Override
        public void clearWarnings() throws SQLException {
            proxy.clearWarnings();
        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
            return proxy.createStatement(resultSetType, resultSetConcurrency);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            return proxy.prepareStatement(sql, resultSetType, resultSetConcurrency);
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            return proxy.prepareCall(sql, resultSetType, resultSetConcurrency);
        }

        @Override
        public Map<String, Class<?>> getTypeMap() throws SQLException {
            return proxy.getTypeMap();
        }

        @Override
        public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
            proxy.setTypeMap(map);
        }

        @Override
        public void setHoldability(int holdability) throws SQLException {
            proxy.setHoldability(holdability);
        }

        @Override
        public int getHoldability() throws SQLException {
            return proxy.getHoldability();
        }

        @Override
        public Savepoint setSavepoint() throws SQLException {
            return proxy.setSavepoint();
        }

        @Override
        public Savepoint setSavepoint(String name) throws SQLException {
            return proxy.setSavepoint(name);
        }

        @Override
        public void rollback(Savepoint savepoint) throws SQLException {
            proxy.rollback(savepoint);
        }

        @Override
        public void releaseSavepoint(Savepoint savepoint) throws SQLException {
            proxy.releaseSavepoint(savepoint);
        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return proxy.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return proxy.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return proxy.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
            return proxy.prepareStatement(sql, autoGeneratedKeys);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
            return proxy.prepareStatement(sql, columnIndexes);
        }

        @Override
        public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
            return proxy.prepareStatement(sql, columnNames);
        }

        @Override
        public Clob createClob() throws SQLException {
            return proxy.createClob();
        }

        @Override
        public Blob createBlob() throws SQLException {
            return proxy.createBlob();
        }

        @Override
        public NClob createNClob() throws SQLException {
            return proxy.createNClob();
        }

        @Override
        public SQLXML createSQLXML() throws SQLException {
            return proxy.createSQLXML();
        }

        @Override
        public boolean isValid(int timeout) throws SQLException {
            return proxy.isValid(timeout);
        }

        @Override
        public void setClientInfo(String name, String value) throws SQLClientInfoException {
            proxy.setClientInfo(name, value);
        }

        @Override
        public void setClientInfo(Properties properties) throws SQLClientInfoException {
            proxy.setClientInfo(properties);
        }

        @Override
        public String getClientInfo(String name) throws SQLException {
            return proxy.getClientInfo(name);
        }

        @Override
        public Properties getClientInfo() throws SQLException {
            return proxy.getClientInfo();
        }

        @Override
        public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
            return proxy.createArrayOf(typeName, elements);
        }

        @Override
        public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
            return proxy.createStruct(typeName, attributes);
        }

        @Override
        public void setSchema(String schema) throws SQLException {
            proxy.setSchema(schema);
        }

        @Override
        public String getSchema() throws SQLException {
            return proxy.getSchema();
        }

        @Override
        public void abort(Executor executor) throws SQLException {
            proxy.abort(executor);
        }

        @Override
        public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
            proxy.setNetworkTimeout(executor, milliseconds);
        }

        @Override
        public int getNetworkTimeout() throws SQLException {
            return proxy.getNetworkTimeout();
        }

        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            return proxy.unwrap(iface);
        }

        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            return proxy.isWrapperFor(iface);
        }
    }
}
